import {
  Body,
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Post,
  Query,
  Req,
} from '@nestjs/common';
import Redis from 'ioredis';
import { InjectRedis } from '@nestjs-modules/ioredis';
import { ApiTags } from '@nestjs/swagger';

import { UserService } from './user.service';
import { AdminUserPageReqDto } from './dto/admin-user.dto';
import { JwtPass } from '@/core/decorator';
import { AdminLoginUserDto, CaptchaResultDto } from './dto/admin-user.dto';
import { CaptchaTool } from '@/utils/tool';

@ApiTags('后台/用户')
@Controller('admin/user')
export class AdminUserController {
  private captcha = new CaptchaTool();

  constructor(
    private readonly userService: UserService,
    @InjectRedis() private readonly redis: Redis,
  ) {}

  /**
   * 用户列表
   */
  @Get()
  async userList(@Query() query: AdminUserPageReqDto) {
    return await this.userService.findAllForPage(query);
  }

  /**
   * 用户登录,返回 token
   */
  @Post('login')
  @JwtPass()
  async loginUser(@Req() req: Request, @Body() data: AdminLoginUserDto) {
    const isValid = this.captcha.verifyCaptcha(req.session, 'admin', data.code);
    if (!isValid) {
      throw new HttpException('验证码错误', HttpStatus.BAD_REQUEST);
    }
    return await this.userService.adminLogin(data);
  }

  /**
   * 验证码
   */
  @Get('captcha')
  @JwtPass()
  getCaptcha(@Req() req: Request): CaptchaResultDto {
    // return await this.userService.createCaptcha(phone);
    const captcha = this.captcha.generateCaptcha();
    this.captcha.setCaptcha(req.session, 'admin', captcha.text);

    return captcha;
  }
}
